package com.nowcoder.community.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: shuhuang
 * @description:Gitee图床工具类
 * @Date: 2023/2/15 21:04
 * @Version java version 1.8
 */
public class GiteeImgBedUtil {
    private static final Logger logger = LoggerFactory.getLogger("ERROR_LOGGER");

    /**
     * 码云私人令牌
     */
    private static final String ACCESS_TOKEN = "0102d1e9cb999910a0fc91b385fc59ff";

    /**
     * 码云个人空间名
     */
    private static final String OWNER = "yang_codeSpace";

    /**
     * 上传指定仓库
     */
    private static final String REPO = "cloud-notepad";

    /**
     * API
     * 新建(POST)、获取(GET)、删除(DELETE)文件：()中指的是使用对应的请求方式
     * %s =>仓库所属空间地址(企业、组织或个人的地址path)  (owner)
     * %s => 仓库路径(repo)
     * %s => 文件的路径(path)
     */
    private static final String API_CREATE_POST = "https://gitee.com/api/v5/repos/%s/%s/contents/%s";

    /**
     * 上传文件
     *
     * @param path          指定存储在哪个文件夹下的路径(例如：/images)
     * @param multipartFile 文件
     * @return 返回文件下载路径(/ images / 文件名)
     */
    public static Map<String, Object> upload(String path, MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        //获取目标文件的上传url
        String targetUrl = GiteeImgBedUtil.createUploadFileUrl(path, originalFilename);
        //请求体封装
        Map<String, Object> map;
        try {
            map = GiteeImgBedUtil.getUploadBodyMap(multipartFile.getBytes());
        } catch (IOException e) {
            logger.error("图片上传发生异常：{}", e.getMessage());
            throw new RuntimeException("上传文件失败，服务器异常！");
        }
        // 借助HttpUtil工具类发送POST请求
        String result = HttpUtil.post(targetUrl, map, 10 * 1000);
        //解析成json字符串
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //请求失败
        if (jsonObject.getObj("commit") == null) {
            logger.error("图片上传失败，无法访问到Gitee图床");
            return CommonUtil.toResponseBody(408, "请求超时~", null);
        }
        //请求成功，返回下载地址
        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));
        return CommonUtil.toResponseBody(200, "图片上传成功！",
                content.getObj("download_url").toString());
    }

    /**
     * 生成上传文件的路径
     */
    private static String createUploadFileUrl(String path, String originalFilename) {
        //获取文件后缀(.jpg)
        String suffix = originalFilename.contains(".") ?
                originalFilename.substring(originalFilename.indexOf(("."))) : null;
        //拼接存储图片的名称
        String uploadDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String filename = uploadDate + "-" + (UUID.randomUUID().toString()).substring(0, 8) + suffix;
        //填充请求路径
        String requestUrl = String.format(API_CREATE_POST, OWNER, REPO, path + "/" + filename);
        return requestUrl;
    }

    /**
     * 获取创建文件的请求体map集合：access_token、description、content
     *
     * @param multipartFile 文件字节数组
     * @return 封装成map的请求体集合
     */
    private static Map<String, Object> getUploadBodyMap(byte[] multipartFile) {
        HashMap<String, Object> bodyMap = new HashMap<>(3);
        bodyMap.put("access_token", ACCESS_TOKEN);
        bodyMap.put("message", "add picture");
        bodyMap.put("content", Base64.encode(multipartFile));
        return bodyMap;
    }


}
